import axios from 'axios'
import { Message, MessageBox, Notification } from 'element-ui'

const service = axios.create({
  baseURL: `http://${process.env.BASE_URL || 'localhost'}:${process.env.PORT || 8222}`,
  timeout: 10000,
  headers: {}
});

// request interceptor
service.interceptors.request.use(config => {
  // Do something before request is sent
  if (config.url == undefined) {
    Notification({
      title: '警告',
      message: '请求路径错误，请检查！',
      type: 'warning',
      offset: 100,
      duration: 2000
    });
    return false
  }
  // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
  //config.headers['X_Innovate_Session'] = getToken() 
  // config.headers['X_Token'] = getToken()
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone interceptor
service.interceptors.response.use(
  // response => response,
  /**
   * 下面的注释为通过在response里，自定义code来标示请求状态
   * 当code返回如下情况则说明权限有问题，登出并返回到登录页
   * 如想通过xmlhttprequest来状态码标识 逻辑可写在下面error中
   * 以下代码均为样例，请结合自生需求加以修改，若不需要，则可删除
   */
  response => {
    if((res)){
      var res = response.data
      if (response.status == 200 && res.code === 20000) {
        return response
      } else {
        if (res.code === 410) {
          Message.warning('登录过期，请重新登录！')
        } 
        else if (res.code === 411) {
          Message.warning(res.message)
        }
        else if (res.code === 412) {
          Message.warning(res.message)
        }
        else if (res.code === 413) {
          Message.warning(res.message)
        } else {
          Message.error(res.msg)
        }
        return Promise.reject('error')
      }
    }else{
      console.log("in")
      if (response.status == 200) {
        return response
      }else{
        Message.warning(response)
      }
      return Promise.reject('error')
    }
  },
  /**
  *	错误回调
  *	*/

  error => {
    console.error('err:' + error) // for debug
    if (error.request.status == '401') {
      Message.warning('登录过期，请重新登录！')

    } else if (error.request.status == '404') {
      Message({
        message: '错误的请求！',
        type: 'error',
        duration: 5 * 1000
      })
    } else if (error.request.status == '500') {
      Message({
        message: '服务器异常！',
        type: 'error',
        duration: 5 * 1000
      })
    } else {
      Message({
        message: '请求失败,请检查您的输入',
        type: 'error',
        duration: 5 * 1000
      })
      //router.push({ path: '/404' })
      return Promise.reject(error)
    }
  })

export default service